import { dbUtils } from '../core'

export interface StoreShopFoodSkuRow {
    id: string
    food_sku_id: string
    food_id: string
    foodgroup_id: string
    image_id: string
    food_sku_no: string
    price: number
    line_price: number
    member_price: number
    unit: string
    food_props: string
    spec_value_ids: string
    is_weight: number
    is_delete: number
    store_id: string
    create_time: number
    update_time: number
}

export const storeShopFoodSkuRepository = {
    upsertBatch(rows: StoreShopFoodSkuRow[]): void {
        if (!rows || rows.length === 0) return
        dbUtils.transaction(() => {
            const sql = `INSERT INTO store_shop_food_sku (
                id, food_sku_id, food_id, foodgroup_id, image_id, food_sku_no, price, line_price, member_price,
                unit, food_props, spec_value_ids, is_weight, is_delete, store_id, create_time, update_time
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
            )
            ON CONFLICT(id) DO UPDATE SET
                food_sku_id=excluded.food_sku_id,
                food_id=excluded.food_id,
                foodgroup_id=excluded.foodgroup_id,
                image_id=excluded.image_id,
                food_sku_no=excluded.food_sku_no,
                price=excluded.price,
                line_price=excluded.line_price,
                member_price=excluded.member_price,
                unit=excluded.unit,
                food_props=excluded.food_props,
                spec_value_ids=excluded.spec_value_ids,
                is_weight=excluded.is_weight,
                is_delete=excluded.is_delete,
                store_id=excluded.store_id,
                create_time=excluded.create_time,
                update_time=excluded.update_time,
                updated_at=CURRENT_TIMESTAMP`

            for (const r of rows) {
                dbUtils.execute(sql, [
                    r.id, r.food_sku_id, r.food_id, r.foodgroup_id, r.image_id, r.food_sku_no, r.price, r.line_price, r.member_price,
                    r.unit, r.food_props, r.spec_value_ids, r.is_weight, r.is_delete, r.store_id, r.create_time, r.update_time
                ])
            }
        })
    },

    listByFood(food_id: string) {
        return dbUtils.query(`SELECT * FROM store_shop_food_sku WHERE food_id = ? AND is_delete = 0`, [food_id])
    }
}

export default storeShopFoodSkuRepository


